package com.goldcn.cart.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goldcn.cart.dao.GoodsCartMapper;
import com.goldcn.cart.dto.GoodsCartDto;
import com.goldcn.cart.dto.UpdateGoodsCartDto;
import com.goldcn.cart.model.GoodsCart;
import com.goldcn.cart.vo.GoodsCartVo;
import com.goldcn.common.CommonTools;
import com.goldcn.common.DataUtils;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dao.GoodsSkuMapper;
import com.goldcn.goods.dao.GoodsSkuShopMapper;
import com.goldcn.goods.dto.GoodsInfoWithSkuDto;
import com.goldcn.goods.dto.PageInfo;
import com.goldcn.goods.model.GoodsInfo;
import com.goldcn.goods.model.GoodsSku;
import com.goldcn.goods.model.GoodsSkuShop;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dto.UserInfoForOrderDto;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/15.
 */
@Service
public class GoodsCartService {

    @Autowired
    private GoodsCartMapper goodsCartMapper;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    GoodsSkuShopMapper goodsSkuShopMapper;
    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    /**
     * 添加商品至我的购物车
     *
     * @param goodsCartVo
     * @return
     */
    @Transactional
    public Object addMyShoppingCart(GoodsCartVo goodsCartVo, Long companyID) {
        //查询商品信息
        GoodsInfoWithSkuDto goodsSku = goodsInfoMapper.selectBySkuID(goodsCartVo.getSkuID());
        if (goodsSku == null) {
            throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
        }
        if (goodsSku.getInventory() < goodsCartVo.getQty()) {
            throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
        }
        //插入前操作
        GoodsCart cart = this.insertCartBefore(goodsCartVo, goodsSku);
        /*if(null==companyID){//根据版本控制companyID
            cart.setCompanyID(companyID);
        }else{
            cart.setCompanyID(goodsCartVo.getCompanyID());
        }*/
        cart.setCompanyID(companyID);
        if (cart.getCartID() == null) {
            cart.setCartID(IdGen.get().nextId());
            return goodsCartMapper.insertSelective(cart);
        } else {
            UpdateGoodsCartDto updateCart = new UpdateGoodsCartDto();
            BeanUtils.copyProperties(cart, updateCart);
            return goodsCartMapper.updateGoodsCartInfo(updateCart);
        }
    }

    @Transactional
    private GoodsCart insertCartBefore(GoodsCartVo goodsCartVo, GoodsInfoWithSkuDto goodsSku) {
        GoodsCart cart = new GoodsCart();
        //查询购物车是否有该商品
        List<GoodsCart> goodsCarts = goodsCartMapper.selectSkuExistInCart(goodsCartVo.getUserID(),
                goodsCartVo.getSkuID());
        if (goodsCarts.size() > 1) {//合并
            int total = 0;
            List<Long> deCarts = new ArrayList<Long>();
            for (GoodsCart goodsCart : goodsCarts) {
                total += goodsCart.getQty();
                deCarts.add(goodsCart.getCartID());
            }
            cart.setCartID(deCarts.get(0));
            deCarts.remove(0);
            BeanUtils.copyProperties(goodsCartVo, cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
            cart.setQty(cart.getQty() + total);
            goodsCartMapper.deleteByPrimaryKey(deCarts);
        } else if (goodsCarts.size() == 1) {
            cart.setCartID(goodsCarts.get(0).getCartID());
            BeanUtils.copyProperties(goodsCartVo, cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
            if (cart.getQty() + goodsCarts.get(0).getQty() > goodsSku.getInventory()) {
                throw CommonTools.createException(ErrorCodeEnum.goodsSkuNoInventory);
            } else {
                cart.setQty(cart.getQty() + goodsCarts.get(0).getQty());
            }
        } else {
            BeanUtils.copyProperties(goodsCartVo, cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
        }
        return cart;
    }

    /**
     * 从购物车移除我的商品(批量)
     *
     * @param cartIDs
     * @return
     */
    public Object removeMyShoppingCart(List<Long> cartIDs) {
        return goodsCartMapper.deleteByPrimaryKey(cartIDs);
    }

    /**
     * 清空购物车
     *
     * @param userID
     * @return
     */
    public Object clearMyShoppingCart(Long userID) {
        return goodsCartMapper.deleteByUserID(userID);
    }

    /**
     * 查询我的购物车
     *
     * @param userID
     * @return
     */
    public Object queryMyShoppingCart(Long shopID, Long userID, Integer pageNum, Integer pageSize) {
        Long VipPriceSW = getVipPriceSW(SystemContext.getCompanyID());
        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page = new Page();
        List<GoodsCartDto> list;
        if (2l == VipPriceSW) {//会员价开启
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(userID);
            list = goodsCartMapper.selectByUserIDorCartIDv2(shopID, userID, null, userInfoForOrderDto.getVipLevel());
        } else {
            list = goodsCartMapper.selectByUserIDorCartIDv2(shopID, userID, null, 1l);
        }
        for (GoodsCartDto dto : list) {
            if (dto.getPriceType().equals(1)) {
                if (shopID == null) {
                    GoodsSku sku = goodsSkuMapper.selectByPrimaryKey(dto.getSkuID());
                    dto.setPrice(String.valueOf(goodsService.getTodayGoldPriceByOtherFee(dto.getSupplierID(), dto.getAttr(), dto.getAttrJson(), sku.getPrice())));
                } else {
                    GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(dto.getSkuID(), shopID);
                    dto.setPrice(String.valueOf(goodsService.getTodayGoldPriceByOtherFee(dto.getSupplierID(), dto.getAttr(), dto.getAttrJson(), skuShop.getOtherFee())));
                }


            }
        }
        page = (Page) list;
        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    /**
     * 查询我的购物车
     *
     * @param cartID
     * @return
     */
    public GoodsCartDto querySingleMyShoppingCart(Long cartID) {
        List<GoodsCartDto> cartDtos = goodsCartMapper.selectByUserIDorCartID(null, cartID);
        return cartDtos.size() == 0 ? null : cartDtos.get(0);
    }

    /**
     * 修改购物车中商品信息（数量）
     *
     * @param goodsCarts
     * @return
     */
    @Transactional
    public Object updateGoodsCartInfo(List<UpdateGoodsCartDto> goodsCarts) {
        int result = 0;
        for (UpdateGoodsCartDto goodsCart : goodsCarts) {
            //判断库存是否充足
            Integer inventory = goodsCartMapper.selectInventoryByCartID(goodsCart.getCartID());
            if (null != inventory && inventory >= goodsCart.getQty()) {
                result += goodsCartMapper.updateGoodsCartInfo(goodsCart);
            } else {
                throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage,
                        "库存上限:" + inventory);
            }
        }
        return result;
    }

    /**
     * 获取会员价开关
     *
     * @param companyID
     * @return
     */
    private Long getVipPriceSW(Long companyID) {
        DataResult result = HttpUtil.httpGet(
                ProConstants.getVipPriceSW + companyID, restTemplate);
        return result.getIsSuccess() == 1 ? Long.valueOf(result.getData().toString()) : 0l;
    }

    //获取下订单需要的UserInfo及其组织信息
    private Object getUserInfoForOrder(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoForOrder + userID, restTemplate);
        //if (jsonObject.get("isSuccess") != 1) {
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("调用base服务获取用户信息接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (UserInfoForOrderDto) JSONObject.toBean(jsonObject.getJSONObject("data"), UserInfoForOrderDto.class);
    }


    public Object selectListByCartIds(List<Long> cardIDs) {
        return goodsCartMapper.selectListByCartIds(cardIDs);
    }
}
